package com.njitt.bysj.srevice;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.njitt.bysj.base.BaseService;
import com.njitt.bysj.bean.ProjectPurchaseBean;
import com.njitt.bysj.mapper.ProjectPurchaseBeanMapper;
import com.njitt.bysj.query.PurchaseQuery;
import com.njitt.bysj.utils.AssertUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: wyj
 * @time: 2022/4/17 20:52
 */
@Service
public class PurchaseService extends BaseService<ProjectPurchaseBean, Integer> {
    @Resource
    private ProjectPurchaseBeanMapper projectPurchaseBeanMapper;

    public void addProjectToSelectPurchaser(Integer projectId) {
        AssertUtil.isTrue(projectId == null || projectId == 0, "添加失败了");
        ProjectPurchaseBean bean = new ProjectPurchaseBean();
        bean.setProjectId(projectId);
        bean.setStatus(0);
        Integer integer = projectPurchaseBeanMapper.insertSelective(bean);
        AssertUtil.isTrue(integer == null || integer == 0, "添加失败");
    }

    public Map<String, Object> queryAllPurchaseProject(PurchaseQuery query) {
        Map<String, Object> map = new HashMap<>(16);
        PageHelper.startPage(query.getPage(), query.getLimit());
        PageInfo<ProjectPurchaseBean> info = new PageInfo<>(projectPurchaseBeanMapper.selectByParams(query));
        map.put("code", 0);
        map.put("data", info.getList());
        map.put("count", info.getTotal());
        map.put("msg", "success");
        return map;
    }


    public ProjectPurchaseBean selectByProjectId(Integer projectId) {
        AssertUtil.isTrue(projectId == null || projectId == 0, "项目号为空");
        ProjectPurchaseBean bean = projectPurchaseBeanMapper.selectByProjectId(projectId);
        AssertUtil.isTrue(bean == null, "查询失败");
        return bean;
    }

    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional(propagation = Propagation.REQUIRED)
    public void updatePurchaseByProjectId(ProjectPurchaseBean projectPurchaseBean) {
        // 首先判断是否指派过了
        ProjectPurchaseBean projectPurchaseBean1 = projectPurchaseBeanMapper.selectByPrimaryKey(projectPurchaseBean.getId());
        AssertUtil.isTrue(projectPurchaseBean1 == null, "指派失败0");
        AssertUtil.isTrue(projectPurchaseBean.getId() == null, "指派失败1");
        AssertUtil.isTrue(projectPurchaseBean.getPurchaserId() == null, "指派失败2");
        AssertUtil.isTrue(projectPurchaseBean.getPurchaserId().equals(projectPurchaseBean1.getPurchaserId()), "重复指派");
        projectPurchaseBean.setStatus(1);
        Integer integer = projectPurchaseBeanMapper.updateByPrimaryKeySelective(projectPurchaseBean);
        AssertUtil.isTrue(integer == null || integer == 0, "指派失败3");
    }
}
